package com.zx.mes.hyl.upms.shiro;


import java.util.HashSet;
import java.util.List;

import java.util.Set;

import com.zx.mes.hyl.common.util.MD5Util;
import com.zx.mes.hyl.upms.dao.RoleRepository;
import com.zx.mes.hyl.upms.dao.UserRepository;
import com.zx.mes.hyl.upms.model.Tresource;
import com.zx.mes.hyl.upms.model.Trole;
import com.zx.mes.hyl.upms.model.Tuser;

import com.zx.mes.hyl.upms.pagemodel.Role;
import com.zx.mes.hyl.upms.service.UserServiceI;
import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AccountException;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;

import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import org.springframework.beans.factory.annotation.Autowired;


/**

 * shiro身份校验核心类

 *

 * @author hyl

 * @date 2017-12-5

 */

public class MyShiroRealm extends AuthorizingRealm {

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private RoleRepository roleRepository;

    //用户登录次数计数  redisKey 前缀

    private String SHIRO_LOGIN_COUNT = "shiro_login_count_";

    //用户登录是否被锁定    一小时 redisKey 前缀

    private String SHIRO_IS_LOCK = "shiro_is_lock_";

    /**

     * 认证信息.(身份验证) : Authentication 是用来验证用户身份

     *

     * @param authcToken

     * @return

     * @throws AuthenticationException

     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(
            AuthenticationToken authcToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
        String name = token.getUsername();
        String password = String.valueOf(token.getPassword());



        //密码进行加密处理  明文为
        String pwd = password;
        String pwdMD5 = MD5Util.md5(pwd);


        Tuser tuser=userRepository.findByNameAndPwd(name,pwdMD5);


        if (null == tuser) {
            throw new AccountException("帐号或密码不正确！");
        }else{
            //登录成功

        }
        Logger.getLogger(getClass()).info("身份认证成功，登录用户："+name +" 密码:"+pwdMD5);
        return new SimpleAuthenticationInfo(tuser, password, getName());
    }

    /**

     * 授权

     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(
            PrincipalCollection principals) {
        System.out.println("权限认证方法：MyShiroRealm.doGetAuthorizationInfo()");
        Tuser user = (Tuser) SecurityUtils.getSubject().getPrincipal();
        String userId = user.getId();
        SimpleAuthorizationInfo info =  new SimpleAuthorizationInfo();
        //根据用户ID查询角色（role），放入到Authorization里。
        Set<String> roleSet = new HashSet<>();
        List<Trole> troles=roleRepository.findAllRoleByUserId(userId);

        for (int j=0;j<troles.size();j++){
            roleSet.add(troles.get(j).getId());
        }
        info.setRoles(roleSet);


        //根据用户ID查询权限（permission），放入到Authorization里。
        List<Trole> troleList= roleRepository.findByUserId(userId);
        Set<String> permissionSet = new HashSet<>();
        for (int i=0;i<troleList.size();i++){
            for (Tresource tresource:troleList.get(i).getTresources()){
                permissionSet.add(tresource.getUrl());
            }

        }

        info.setStringPermissions(permissionSet);
        return info;
    }
}